package com.example.homewidgets

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.RemoteViews
import com.example.homewidgets.ui.theme.MySharedPreferences

/**
 *  Widget继承于BroadcastReceiver，需要在manifest中注册
 *  与之匹配的有 AppWidgetProviderInfo 文件：描述应用微件的元数据，如应用微件的布局、更新频率和 AppWidgetProvider 类
 */
class NewAppWidget : AppWidgetProvider() {

    var count: Int = 0

    //onReceive不存在widget生命周期中，它是用来接收广播，通知全局的
    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)

        if (context == null) return

        val appWidgetManager = AppWidgetManager.getInstance(context)
        val remoteViews = RemoteViews(context.packageName, R.layout.new_app_widget)
        val sharedPreferences = MySharedPreferences(context)

        //当我们点击桌面上的widget按钮（这个按钮我们在onUpdate中已经为它设置了监听），widget就会发送广播
        //这个广播我们也在onUpdate中为它设置好了意图，设置了action，在这里我们接收到对应的action并做相应处理
        if (MyActions.CLICK_WidgetSelf == intent?.action) {

            val stringExtra = intent.getStringExtra("key")
            sharedPreferences.saveString("key", "123123")

            // 更新UI
            remoteViews.setTextViewText(R.id.tv, "123123")

            appWidgetManager.updateAppWidget(
                ComponentName(context, NewAppWidget::class.java),
                remoteViews
            )
        } else if (MyActions.CLICK_APP2Widget == intent?.action) {
            val stringExtra = intent.getStringExtra("key")
            sharedPreferences.saveString("key", stringExtra ?: "空的")

            // 更新UI
            remoteViews.setTextViewText(R.id.tv, stringExtra)

            appWidgetManager.updateAppWidget(ComponentName(context, NewAppWidget::class.java),remoteViews)
        }
    }

    /// 此方法可以按 AppWidgetProviderInfo 中的 updatePeriodMillis 属性定义的时间间隔来更新应用微件
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        // 可能有多个活动部件，因此更新所有部件
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    companion object {
        fun updateAppWidget(
            context: Context,
            appWidgetManager: AppWidgetManager,
            appWidgetId: Int
        ) {
            // 更改文本
            val sharedPreferences = MySharedPreferences(context)
            var string = sharedPreferences.getString("key", defaultValue = "")
            if (string.isEmpty()) {
                string = context.getString(R.string.appwidget_text)
            }
            println("string = $string")

            // btn添加意图
            val intent = Intent(context, NewAppWidget::class.java).apply {
                setAction(MyActions.CLICK_WidgetSelf)
                putExtra("key", "value")
            }
            val pendingIntent =
                PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)


            // 添加另一个意图:唤起主app
            val intentMain = Intent(context, MainActivity::class.java).apply {
                putExtra("widgetId", appWidgetId)
                putExtra("extraString", "This is a string")

                flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
            }
            val pendingIntentMain = PendingIntent.getActivity(
                context,
                appWidgetId,
                intentMain,
                PendingIntent.FLAG_UPDATE_CURRENT
            )

            // 不启动app，通知到app
            val serverIntent = Intent(context, MyWidgetService::class.java).apply {
                setAction(MyActions.CLICK_Widget2App)
                putExtra("key", "value")
            }
            val serverPendingIntent = PendingIntent.getService(context, 0, serverIntent, PendingIntent.FLAG_UPDATE_CURRENT)


            // 当前view布局对象
            val views = RemoteViews(context.packageName, R.layout.new_app_widget).apply {
                setTextViewText(R.id.tv, string)
                setOnClickPendingIntent(R.id.btn, pendingIntent)
                setOnClickPendingIntent(R.id.btnMain, pendingIntentMain)
                setOnClickPendingIntent(R.id.serverMain,serverPendingIntent)
            }

            //告诉AppWidgetManager对当前应用程序小部件执行更新
            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }

    /// 首次创建应用微件的实例时，会调用此方法。
    override fun onEnabled(context: Context) {

    }

    /// 从应用微件托管应用中删除了应用微件的最后一个实例时，会调用此方法。
    override fun onDisabled(context: Context) {

    }

    /// 每删除一次窗口小部件就调用一次
    override fun onDeleted(context: Context?, appWidgetIds: IntArray?) {
        super.onDeleted(context, appWidgetIds)
    }

    /// 当小部件大小改变时
    override fun onAppWidgetOptionsChanged(
        context: Context?,
        appWidgetManager: AppWidgetManager?,
        appWidgetId: Int,
        newOptions: Bundle?
    ) {
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
        if (newOptions == null) return
        if (context == null) return

        // 获取小部件的最新尺寸参数
//        val minWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)

        // 根据尺寸参数决定加载哪个布局
//        val layoutId = if (minWidth <= 203) {
//            R.layout.a_layout
//        } else if (minWidth <= 276) {
//            R.layout.b_layout
//        }
//        else {
//            R.layout.c_layout
//        }

        val layoutId = R.layout.new_app_widget

        // 更新小部件的布局
        val views = RemoteViews(context.packageName, layoutId)
        appWidgetManager?.updateAppWidget(appWidgetId, views)
    }


}
